package edu.hrbu.trade01.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import edu.hrbu.trade01.annotation.MyLog;
import edu.hrbu.trade01.entity.Assist;
import edu.hrbu.trade01.service.AssistService;
import edu.hrbu.trade01.util.R;
import edu.hrbu.trade01.vo.AssistSaveVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static edu.hrbu.trade01.util.ConstUtil.LOG_TITLE_SAVE;
import static edu.hrbu.trade01.util.ConstUtil.LOG_TYPE_NEWS;

/**
 * @author 徐登宇
 */
@Slf4j
@RestController
@RequestMapping("/assist")
public class AssistController {

    @Resource(name = "assistServiceImpl")
    private AssistService assistService;

    @RequestMapping("/list")
    public R list() {
        return R.ok(assistService.list());
    }

    @MyLog(title = LOG_TITLE_SAVE, businessType = LOG_TYPE_NEWS)
    @Transactional
    @PostMapping("/save")
    public R save(@RequestBody String param) {
        List<Object> objects = JSONUtil.toList(param, Object.class);
        log.error("@"+ objects);
        ArrayList<Assist> assists = new ArrayList<>();
        for (Object obj:objects){
            Assist assist=JSONUtil.toBean(JSONUtil.toJsonStr(obj), Assist.class);
            assists.add(assist);
        }
        // 先删除所有
        assistService.remove(null);
        // 再添加
        assistService.saveBatch(assists);

        return R.ok();
    }

}
